#include <stdio.h>
#include "com_whyun_jni_chapter2_StructDemo.h"
static char *randStr = "wertyui";
/*
 * Class:     com_whyun_jni_chapter2_StructDemo
 * Method:    getSum
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_whyun_jni_chapter2_StructDemo_getSum__II
	(JNIEnv *env, jobject obj, jint a, jint b) {
		return a+b;
};

/*
 * Class:     com_whyun_jni_chapter2_StructDemo
 * Method:    getSum
 * Signature: ([B)I
 */
JNIEXPORT jint JNICALL Java_com_whyun_jni_chapter2_StructDemo_getSum___3B
  (JNIEnv *env, jobject obj, jbyteArray arr) {
	  int sum = 0;
	  char *data = (char*)(*env)->GetByteArrayElements(env,arr,NULL);
	  int dataLen = (int)(*env)->GetArrayLength(env,arr);
	  int i = 0;
	  for (i=0;i<dataLen;i++) {
		  sum += data[i];
	  }
	  (*env)->ReleaseByteArrayElements(env,arr,data,0);
	  return (jint)sum;
}

/*
 * Class:     com_whyun_jni_chapter2_StructDemo
 * Method:    getUserList
 * Signature: (I)Ljava/util/ArrayList;
 */
JNIEXPORT jobject JNICALL Java_com_whyun_jni_chapter2_StructDemo_getUserList
  (JNIEnv *env, jobject obj, jint num) {
	int count = (int)num,i=0;
	jclass clsUserBean = (*env)->FindClass(env,"com/whyun/jni/bean/UserBean");
	jclass clsArrayList = (*env)->FindClass(env,"java/util/ArrayList");
	jmethodID userBeanConstructor = (*env)->GetMethodID(env,clsUserBean,"<init>","()V");
	jmethodID userBeanSetAge = (*env)->GetMethodID(env,clsUserBean,"setAge","(I)V");
	jmethodID userBeanSetName = (*env)->GetMethodID(env,clsUserBean,"setName","(Ljava/lang/String;)V");
	jmethodID arrayListContructor = (*env)->GetMethodID(env,clsArrayList,"<init>","(I)V");
	jmethodID arrayListAdd = (*env)->GetMethodID(env,clsArrayList,"add","(ILjava/lang/Object;)V");

	jobject arrayList = (*env)->NewObject(env,clsArrayList,arrayListContructor,num);

	char nameStr[5] = {0};
	int index = 0;
	jstring name;

	for(i=0;i<count;i++) {
		jobject userBean = (*env)->NewObject(env,clsUserBean,userBeanConstructor);
		
		for (index=0;index<4;index++) {
			nameStr[index] = randStr[(i+7)%5];
		}
		name = (*env)->NewStringUTF(env,(const char *)nameStr);
		(*env)->CallVoidMethod(env,userBean,userBeanSetAge,(jint)(20+i));
		(*env)->CallVoidMethod(env,userBean,userBeanSetName,name);

		(*env)->CallVoidMethod(env,arrayList,arrayListAdd,(jint)i,userBean);
	}
	return arrayList;
}

/*
 * Class:     com_whyun_jni_chapter2_StructDemo
 * Method:    showException
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_whyun_jni_chapter2_StructDemo_showException
  (JNIEnv *env, jobject obj) {
	  jclass exception = (*env)->FindClass(env,"java/lang/Exception");
	  (*env)->ThrowNew(env,exception,"This is a exception.");
}
